<!--
 * @Author: lwHao
 * @Date: 2020-09-20 15:31:01
 * @LastEditors: lwHao
 * @LastEditTime: 2020-09-20 16:31:10
-->
<template>
  <div class="article-meta">
    <nuxt-link :to="{name:'profile',params:{username:article.author.username}}">
      <img :src="article.author.image" />
    </nuxt-link>
    <div class="info">
      <nuxt-link :to="{name:'profile',params:{username:article.author.username}}" href class="author" :style="{color:authorColor}">{{article.author.username}}</nuxt-link>
      <span class="date">{{article.createdAt | date('MMM DD,YYYY')}}</span>
    </div>
    <button class="btn btn-sm btn-outline-secondary" @click="onFallow(article.author.username)" :disabled="followDisable">
      <i class="ion-plus-round"></i>
      &nbsp;
      {{article.author.following ? 'Unfollow' : 'Follow'}} {{article.author.username}}
    </button>
    &nbsp;&nbsp;
    <button class="btn btn-sm btn-outline-primary" @click="onFavoirte(article.slug)">
      <i class="ion-heart"></i>
      &nbsp;
      {{ article.favorited ? 'Unfavorite' : 'Favorite' }} Article
      <span class="counter">({{ article.favoritesCount }})</span>
    </button>
  </div>
</template>

<script>
import { followUser, unfollowUser } from '@/api/profiles'
import { deleteFavorite, addFavorite } from '@/api/article'
export default {
  name: 'article-meta',
  props: {
    article: {
      type: Object,
      required: true
    },
    authorColor: {
      type: String,
      default: 'white'
    }
  },
  data() {
    return {
      favoriteDisable: false,
      followDisable: false,
    }
  },
  methods: {
    async onFallow(username) {
      this.followDisable = true
      try {
        const followAction = this.article.author.following ? unfollowUser : followUser
        const response = await followAction(username)
        const { following } = response.data.profile
        this.article.author.following = following
      } finally {
        this.followDisable = false
      }
    },
    async onFavoirte(slug) {
      this.favoriteDisable = true
      try {
        const favAction = this.article.favorited ? deleteFavorite: addFavorite
        const response = await favAction(slug)
        const { favorited, favoritesCount } = response.data.article
        this.article.favorited = favorited
        this.article.favoritesCount = favoritesCount
      } finally {
        this.favoriteDisable = false
      }
    }
  }

}
</script>

<style>
</style>